﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ayxjDllClass
{
    public class UdpClass
    {
        public Socket UdpClient { get; set; } = null;
        EndPoint serverPoint = new IPEndPoint(IPAddress.Any, 0);
        Thread receiveData = null;

        public UdpClass(int Port)
        {
            UdpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            UdpClient.Bind(new IPEndPoint(IPAddress.Any, Port));
            receiveData = new Thread(new ThreadStart(ReceiveMessage));
            receiveData.Start();
        }

        public delegate void HandleMessage(byte[] bytes, EndPoint endPoint);
        public HandleMessage HandleMessageEvent = null;

        async void ReceiveMessage()
        {
            while (UdpClient != null)
            {
                try
                {
                    byte[] data = new byte[10240];
                    int len = UdpClient.ReceiveFrom(data, ref serverPoint);
                    if (len > 0)
                    {
                        byte[] buffer = new byte[len];
                        Array.Copy(data, buffer, len);
                        if (HandleMessageEvent != null)
                        {
                            HandleMessageEvent(buffer, serverPoint);
                        }
                    }
                    Thread.Sleep(100);
                }
                catch { }
            }
        }

        public int SendMessage(byte[] data, EndPoint remotEd)
        {
            return UdpClient.SendTo(data, remotEd);
        }
    }
}
